using ShopPowerTemplate.Common.Validation;
using System;
using System.Text.RegularExpressions;

namespace ShopPowerTemplate.ValidationControls
{
    public class EmailValidationControl : ValidationControl
    {
        public EmailValidationControl()
            : base()
        {
            ValidationMessage.Text = "* Invalid email format";
        }

        public override bool Validate()
        {
            String stringToValidate = PropertyToValidate as String;
            if (string.IsNullOrEmpty(stringToValidate))
            {
                ValidationMessage.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                return true;
            }
            else if (IsValidEmail(stringToValidate))
            {
                ValidationMessage.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                return true;
            }
            else
            {
                ValidationMessage.Visibility = Windows.UI.Xaml.Visibility.Visible;
                return false;
            }
        }

        private bool IsValidEmail(string inputEmail)
        {
            string strRegex = @"^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@(([0-9a-zA-Z])+([-\w]*[0-9a-zA-Z])*\.)+[a-zA-Z]{2,9})$";
            Regex re = new Regex(strRegex);
            if (re.IsMatch(inputEmail))
                return (true);
            else
                return (false);
        }
    }
}
